﻿using System;
using System.Data;
using System.Text;
using System.Collections.Generic;
using System.Linq;
 
using WinnerCMS.Common;
using WinnerCMS.Model;

namespace WinnerCMS.Data 
{
    /// <summary>
    /// 热门关键字
    /// </summary>
    public class HotKeyWordsDal 
    {
        /// <summary>
        /// 添加热门关键字
        /// </summary>
        /// <param name="modelId"></param>
        /// <param name="keyWord"></param>
        /// <param name="result"></param>
        public void Add(byte modelId, string keyWord, int result)
        {
            using (Entities db = new Entities())
            {
                var info = db.HotKeyWords.FirstOrDefault(x => x.ModelId == modelId && x.KeyWord == keyWord);
                if (info == null)
                {
                    info = db.HotKeyWords.Create();
                    info.ModelId = modelId;
                    info.KeyWord = keyWord;
                    info.Hits = 1;
                    info.Result = result;
                    info.LastHitTime = DateTime.Now;

                    db.HotKeyWords.Add(info);
                }
                else
                {
                    info.ModelId = modelId;
                    info.KeyWord = keyWord;
                    info.Hits = info.Hits + 1;
                    info.Result = result;
                    info.LastHitTime = DateTime.Now;
                }
                db.SaveChangesAsync().Wait();
            }

        }
        /// <summary>
        /// 取得热门关键字排行榜
        /// </summary>
        /// <param name="topNum"></param>
        /// <returns></returns>
        public IList<HotKeyWord> GetList(int topNum)
        {
            using (Entities db = new Entities())
            {
                return db.HotKeyWords.OrderByDescending(x => x.LastHitTime).ThenByDescending(x => x.Hits).Take(topNum).ToList();
            }
        }
    }
}